package cn.sumpu.app.guoguojie.web.mvc.family;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import cn.sumpu.app.guoguojie.biz.AlbumBiz;
import cn.sumpu.app.guoguojie.biz.CodeBiz;
import cn.sumpu.app.guoguojie.biz.DetailBiz;
import cn.sumpu.app.guoguojie.biz.ExperBiz;
import cn.sumpu.app.guoguojie.biz.FamilyBiz;
import cn.sumpu.app.guoguojie.biz.ImageBiz;
import cn.sumpu.app.guoguojie.biz.MemberBiz;
import cn.sumpu.app.guoguojie.domain.Album;
import cn.sumpu.app.guoguojie.domain.Code;
import cn.sumpu.app.guoguojie.domain.Detail;
import cn.sumpu.app.guoguojie.domain.Family;
import cn.sumpu.app.guoguojie.domain.Learning;
import cn.sumpu.app.guoguojie.domain.Member;
import cn.sumpu.app.guoguojie.domain.Personality;
import cn.sumpu.app.guoguojie.domain.Picture;
import cn.sumpu.app.guoguojie.domain.Work;
import cn.sumpu.app.guoguojie.domain.Ext.Baby;
import cn.sumpu.app.guoguojie.domain.Ext.ImageWeb;
import cn.sumpu.app.guoguojie.exception.AppBusinessException;
import cn.sumpu.app.guoguojie.util.Common;
import cn.sumpu.app.guoguojie.util.Encode;

@Controller
public class MemberController {
	@Autowired
	private DetailBiz detailBiz;
	@Autowired
	public CodeBiz codeBiz;
	@Autowired
	public ExperBiz experBiz;
	@Autowired
	public MemberBiz memberBiz;
	@Autowired
	public ImageBiz imageBiz;
	@Autowired
	public AlbumBiz albumBiz;
	@Autowired
	private FamilyBiz familyBiz;
	
	/**
	 * 查看会员详细信息
	 * author Bruce Zhang
	 * @param request
	 * @param memberId	会员ID
	 * @return
	 */
	@RequestMapping(value = "/memberDetail.htm", method = RequestMethod.GET)
	public String memberDetail(HttpServletRequest request, String memberId) {
		try {
			Member member = (Member)request.getSession().getAttribute("member");
			if(memberId != (member.getIdentifier())){
				member = memberBiz.getMemberById(memberId);
			}
			//根据门牌号查询家的信息
			Family family = familyBiz.getFamilyByDoor(member.getFamily());
			//根据会员ID查询会员的信息
			Detail detail = detailBiz.getDetailAll(memberId);
			//根据门牌号查询家的成员的信息
			List<Member> memberList = memberBiz.getMemberListByDoorplate(member.getFamily());
			request.setAttribute("member", member);
			request.setAttribute("family", family);
			request.setAttribute("detail", detail);
			request.setAttribute("memberList", memberList);
		} catch (AppBusinessException e) {
			e.printStackTrace();
		}
		return "member/memberDetail";
	}
	
	/**
	 * author Bruce Zhang
	 * @param request
	 * @return 会员信息页面
	 */
	@RequestMapping(value = "/memberInfo.htm", method = RequestMethod.GET)
	public String memberInfo(HttpServletRequest request) {
		try {
			Member member = (Member)request.getSession().getAttribute("member");
			List<Member> memberList = memberBiz.getParentListByDoorplate(member.getFamily());
			request.setAttribute("memberList", memberList);
			return "member/memberInfo";
		} catch (AppBusinessException e) {
			e.printStackTrace();
			return "common/error";
		}
	}
	
	/**
	 * author Bruce Zhang
	 * @param request
	 * @param response
	 * @return	修改家的基本资料的页面
	 * @throws AppBusinessException
	 */
	@RequestMapping(value = "/familyInfo.htm")
	public String familyInfo(HttpServletRequest request,HttpServletResponse response) throws AppBusinessException{
		Member member = (Member)request.getSession().getAttribute("member"); 
		List<Member> memberList = memberBiz.getParentListByDoorplate(member.getFamily());
		request.setAttribute("memberList", memberList);
		return "member/familyInfo";
	}
	
	//跳转至登录用户的基本信息页面
	@RequestMapping(value = "/baseInfo.htm")
	public String baseInfo(String memberId, HttpServletRequest request,HttpServletResponse response) throws AppBusinessException{
		Member member = (Member) request.getSession().getAttribute("member");
		try{
			if(memberId != null && !"".equals(memberId) && !member.getIdentifier().equals(memberId)){
				member = memberBiz.getMemberById(memberId);
			}
			Detail detail = detailBiz.getDetailById(member.getIdentifier());
			request.setAttribute("detail", detail);
			request.setAttribute("member", memberBiz.getMemberById(member.getIdentifier()));
			return "member/baseInfo";
		}catch(Exception e){
			e.printStackTrace();
			return "common/error";
		}
	}
	
	//保存登录用户的基本信息
	@RequestMapping(value = "/saveBaseInfo.htm", method = RequestMethod.POST)
	public String saveBaseInfo(String memberId, Member member, Detail detail,HttpServletRequest request,HttpServletResponse response){
		response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        try{ 
			pw = response.getWriter();
			String id = ((Member)request.getSession().getAttribute("member")).getIdentifier();
			if(!"".equals(memberId)){
				id = memberId;
			}
			member.setIdentifier(id);
			detail.setMember(id);
			memberBiz.updateLoginMember(member, detail);
			pw.print("success");
        }catch(Exception e){
        	e.printStackTrace();
        	pw.print("error");
        }
		return null;
	}
	
	@RequestMapping(value = "/avatar.htm")
	public String avatar(String memberId,HttpServletRequest request,HttpServletResponse response) throws AppBusinessException{
		Member member = (Member) request.getSession().getAttribute("member");
		if(memberId != null && !"".equals(memberId) && !member.getIdentifier().equals(memberId)){
			member = memberBiz.getMemberById(memberId);
		}
		request.setAttribute("member", member);
		request.setAttribute("memberId", member.getIdentifier());
		return "member/avatar";
	}
	
	//跳转至全家福的页面
	@RequestMapping(value = "/familyAvatar.htm")
	public String quanJiaFu(HttpServletRequest request,HttpServletResponse response) throws AppBusinessException{
		Member member = (Member) request.getSession().getAttribute("member");
		Family family = familyBiz.getFamilyByMember(member.getIdentifier());
		request.setAttribute("family", family);
		return "member/familyAvatar";
	}
	
	@RequestMapping(value = "/avatarPop.htm")
	public String avatarPop(String type,String memberId,HttpServletRequest request,HttpServletResponse response) throws AppBusinessException{
		request.setAttribute("type", type);
		
		request.setAttribute("memberId", memberId);
		return "member/avatarPop";
	}
	
	@RequestMapping(value = "/avatarPopTab1.htm")
	public String avatarPopTab1(String uploadType,String memberId,HttpServletRequest request,HttpServletResponse response) throws AppBusinessException{
		request.setAttribute("type", uploadType);
		request.setAttribute("memberId", memberId);
		return "member/avatarPopTab1";
	}
	
	@RequestMapping(value = "/avatarPopTab2.htm")
	public String avatarPopTab2(String uploadType,String memberId,HttpServletRequest request,HttpServletResponse response) throws AppBusinessException{
		Member member = (Member) request.getSession().getAttribute("member");
		List<Album> albumList = albumBiz.getAlbumList(member.getFamily());
		request.setAttribute("albumList", albumList);
		if(albumList!=null && albumList.size() > 0){
			Album album = albumList.get(0);
			List<Picture> photoList = albumBiz.getPhotoList(member.getFamily(), album.getIdentifier());
			request.setAttribute("photoList", photoList);
		}
		request.setAttribute("type", uploadType);
		request.setAttribute("memberId", memberId);
		return "member/avatarPopTab2";
	}
	
	@RequestMapping(value = "/avatarPopTab2List.htm")
	public String avatarPopTab2List(String albumId,String uploadType,String memberId,HttpServletRequest request,HttpServletResponse response) throws AppBusinessException{
		Member member = (Member) request.getSession().getAttribute("member");
		List<Picture> photoList = albumBiz.getPhotoList(member.getFamily(), albumId);
		request.setAttribute("photoList", photoList);
		request.setAttribute("type", uploadType);
		request.setAttribute("memberId", memberId);
		return "member/avatarPopTab2List";
	}
	
	
	@RequestMapping(value = "/avatarUpload.htm", method = RequestMethod.POST)
	public String avatarUpload(HttpServletRequest request,HttpServletResponse response) {
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter pw = null;
		try {
			ImageWeb imageWeb = imageBiz.uploadOneImg(request);
			pw = response.getWriter();
			pw.println(JSONObject.fromObject(imageWeb).toString());
		} catch (Exception e) {
			e.printStackTrace();
			try {
				pw = response.getWriter();
				pw.println("Upload failure!");
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}
	
	@RequestMapping(value = "/selectPhoto.htm", method = RequestMethod.POST)
	public String selectPhoto(String photoId,String photoUrl,HttpServletRequest request,HttpServletResponse response) {
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter pw = null;
		try {
			String tmpPath = request.getSession().getServletContext().getRealPath("/")+File.separator+photoUrl;
			ImageWeb imageWeb = new ImageWeb();
			if(!Common.empty(photoUrl)){
				BufferedImage bi = ImageIO.read(new File(tmpPath));
				if(bi!=null){
					imageWeb.setHeight(bi.getHeight());
					imageWeb.setWidth(bi.getWidth());
					imageWeb.setImageUrl(photoUrl);
				}
			}
			pw = response.getWriter();
			pw.println(JSONObject.fromObject(imageWeb).toString());
		} catch (Exception e) {
			e.printStackTrace();
			try {
				pw = response.getWriter();
				pw.println("Upload failure!");
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}
	
	@RequestMapping(value = "/cutAvatarCancel.htm")
	public String cutAvatarCancel(HttpServletRequest request,HttpServletResponse response) throws AppBusinessException{
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter pw = null;
		try {
			pw = response.getWriter();
			
			String webAppPath = request.getSession().getServletContext().getRealPath("/");
			String srcImg = request.getParameter("srcImg");
			String srcImgPath = webAppPath+File.separator+srcImg;
			File f = new File(srcImgPath);
			if(f.exists()){
				f.delete();
			}
			pw.print("success");
		} catch (Exception e) {
			e.printStackTrace();
				pw.print("error");
		}
		return null;
	}
	
	@RequestMapping(value = "/avatarCutDiv.htm")
	public String avatarCutDiv(ImageWeb imageWeb,String type,String photoType,String memberId,HttpServletRequest request,HttpServletResponse response) throws AppBusinessException{
		response.setHeader("Pragma","No-cache");    
        response.setHeader("Cache-Control","no-cache");    
        response.setDateHeader("Expires", 0);
		int height = imageWeb.getHeight();
		int width = imageWeb.getWidth();
		double zoom =(double)height/245;
		double zoom1 = (double)width/255;
		int realWidth = 0;
		int realHeight = 0;
		if(zoom1 > zoom){
			realWidth = 255;
			realHeight = (int)(height / zoom1); 
		}else{
			realWidth =(int) (width / zoom);
			realHeight =245;
		}
		imageWeb.setWidth(realWidth);
		imageWeb.setHeight(realHeight);
		request.setAttribute("imageWeb", imageWeb);
//		上传头像类型(1.会员头像 2.家庭头像 3.baby头像)
		request.setAttribute("type", type);
//		照片类型(1.上传的照片 2.相册中选择的照片)
		request.setAttribute("photoType", photoType);
		request.setAttribute("memberId", memberId);
		
		return "member/avatarCut";
	}
	
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws AppBusinessException
	 */
	@RequestMapping(value = "/avatarCut.htm", method = RequestMethod.POST)
	public String avatarCut(HttpServletRequest request,HttpServletResponse response) throws AppBusinessException {
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter pw = null;
		try {
			pw = response.getWriter();
			String srcImg = request.getParameter("srcImg");
			int x = Integer.parseInt(request.getParameter("x"));
			int y = Integer.parseInt(request.getParameter("y"));
			int w = Integer.parseInt(request.getParameter("w"));
			int h = Integer.parseInt(request.getParameter("h"));
			int realWidth = Integer.parseInt(request.getParameter("realWidth"));
			int realHeight = Integer.parseInt(request.getParameter("realHeight"));
			String cutUrl = memberBiz.cutAvatar(request, srcImg, x, y, w, h, realWidth, realHeight);
			pw.print(cutUrl);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping(value = "/babyInfo.htm")
	public String babyInfo(HttpServletRequest request,HttpServletResponse response) throws AppBusinessException{
		Member member = (Member) request.getSession().getAttribute("member");
		List<Baby> babyList = memberBiz.getBabyList(member.getIdentifier());
		request.setAttribute("babyList", babyList);
		return "member/babyInfo";
	}
	
//	个性资料页面
	@RequestMapping(value = "/memberSpecial.htm", method = RequestMethod.GET)
	public String memberSpecial(String memberId, HttpServletRequest request) {
		Member member = (Member) request.getSession().getAttribute("member");
		Detail detail = null;
		try{
			if(memberId != null && !"".equals(memberId) && !member.getIdentifier().equals(memberId)){
				member = memberBiz.getMemberById(memberId);
			}
			detail = detailBiz.getDetailById(member.getIdentifier()); 
			List<Code> bloodList = codeBiz.getCodeListByType("blood");
			List<Code> constellationList = codeBiz.getCodeListByType("constellation");
			List<Code> profileList = codeBiz.getCodeListByType("profile");
			request.setAttribute("bloodList", bloodList);
			request.setAttribute("constellationList", constellationList);
			request.setAttribute("profileList", profileList);
			if(member != null){
//				detail = detailBiz.getDetailById(member.getIdentifier());
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		request.setAttribute("detail", detail);
		return "member/memberSpecial";
	}
	
	//保存个性资料管理
	@RequestMapping(value = "/saveDetail.htm", method = RequestMethod.POST)
	public String saveDetail(String memberId, HttpServletRequest request,HttpServletResponse response) {
		try{
			Member member = (Member) request.getSession().getAttribute("member");
			Detail detail = null;
	        response.setContentType("text/html; charset=UTF-8");
	        PrintWriter pw = null;
			pw = response.getWriter();
			String escaped_json = request.getParameter("jsonData");//获取提交的参数值,jsonData与上面红体字的jsonData相对应
			String json=Encode.unescape(escaped_json);//将得到的json,进行unescape解析,(Encode是我自定义的类)
			JSONObject jsonObject = JSONObject.fromObject(json);
			Map<String, Class<Personality>> m = new HashMap<String, Class<Personality>>();
			m.put("personalityList", Personality.class);//"personalityList"与js object里的personalityList对应,Personality.class类的字段与客户端new Product(........);具有相同的数据结构
			detail =  (Detail) JSONObject.toBean(jsonObject, Detail.class,m);
			if(memberId != null && !"".equals(memberId) && !member.getIdentifier().equals(memberId)){
				detail.setMember(memberId);
			}else{
				detail.setMember(member.getIdentifier());
			}
			detailBiz.saveDetail(detail);
			pw.print("success");
		}catch(Exception e){
			e.printStackTrace();
			return "common/error";
		}
		return null;
	}
	
	//保存宝宝信息
	@RequestMapping(value = "/saveBabyInfo.htm", method = RequestMethod.POST)
	public String saveBabyInfo(Baby baby,HttpServletRequest request,HttpServletResponse response){
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        
		try{
			pw = response.getWriter();
			String escaped_json = request.getParameter("jsonData");//获取提交的参数值,jsonData与上面红体字的jsonData相对应
			String json=Encode.unescape(escaped_json);//将得到的json,进行unescape解析,(Encode是我自定义的类)
			JSONObject jsonObject = JSONObject.fromObject(json);
			Map<String, Class<Baby>> m = new HashMap<String, Class<Baby>>();
			m.put("babyList", Baby.class);//"personalityList"与js object里的personalityList对应,Personality.class类的字段与客户端new Product(........);具有相同的数据结构
			baby =  (Baby) JSONObject.toBean(jsonObject, Baby.class,m);
			baby.setFamily(((Member) request.getSession().getAttribute("member")).getFamily());
			memberBiz.addBaby(baby);
			pw.print("success");
		}catch(Exception e){
			e.printStackTrace();
			pw.print("error");
		}
		return null;
	}
	
	//保存宝宝信息
	@RequestMapping(value = "/deleteBabyInfo.htm", method = RequestMethod.POST)
	public String deleteBabyInfo(String identifier,HttpServletRequest request,HttpServletResponse response){
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter out = null;
		try{
			memberBiz.deleteBabyInfo(identifier);
			out = response.getWriter();
			out.print("success");
		}catch(Exception e){
			e.printStackTrace();
			out.print("error");
		}
		return null;
	}
	
//	经历页面
	@RequestMapping(value = "/memberExper.htm", method = RequestMethod.GET)
	public String memberExper(String memberId, HttpServletRequest request) {
		Member member = (Member) request.getSession().getAttribute("member");
		try{
			if(memberId != null && !"".equals(memberId) && !member.getIdentifier().equals(memberId)){
				member = memberBiz.getMemberById(memberId);
			}
			List<Learning> learningList = experBiz.getLearningList(member.getIdentifier());
			List<Work> workList = experBiz.getWorkList(member.getIdentifier());
			List<Code> schoolType = codeBiz.getCodeListByType("school_type");
			request.setAttribute("learningList", learningList);
			request.setAttribute("workList", workList);
			request.setAttribute("schoolType", schoolType);
			return "member/memberExper";
		}catch(Exception e){
			e.printStackTrace();
			return "common/error";
		}
	}
	
//	学习经历页面
	@RequestMapping(value = "/memberLearningItem.htm", method = RequestMethod.GET)
	public String memberLearningItem(HttpServletRequest request) {
		String id = (String) request.getParameter("id");
		try{
			Learning l = experBiz.getLearningById(id==null?0:Integer.parseInt(id));
			List<Code> schoolType = codeBiz.getCodeListByType("school_type");
			
			request.setAttribute("schoolType", schoolType);
			request.setAttribute("learning", l);

		}catch(Exception e){
			e.printStackTrace();
		}
		return "member/memberLearningItem";
	
	}
	
//	保存学习经历
	@RequestMapping(value = "/saveLearningItem.htm", method = RequestMethod.POST)
	public String saveLearningItem(String memberId, HttpServletRequest request,HttpServletResponse response) {
		response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
		try{
			pw = response.getWriter();
			Member member = (Member) request.getSession().getAttribute("member");
			String id = (String) request.getParameter("id");
			String schoolType = request.getParameter("schoolType");
			String school = request.getParameter("school");
			String college = request.getParameter("college");
			String className = request.getParameter("className");
			String entryDate = request.getParameter("entryDate");
			Learning learning = new Learning();
			learning.setId(Common.empty(id)?null:Integer.parseInt(id));
			learning.setSchoolType(schoolType);
			learning.setSchool(school);
			learning.setCollege(college);
			learning.setClassName(className);
			learning.setEntryDate(entryDate);
			if(memberId != null && !"".equals(memberId) && !member.getIdentifier().equals(memberId)){
				learning.setMember(memberId);
			}else{
				learning.setMember(member.getIdentifier());
			}
			experBiz.saveLearning(learning);
			pw.print("success");
		}catch(Exception e){
			e.printStackTrace();
			pw.print("error");
		}
		return null;
	
	}
	
//	删除学习经历
	@RequestMapping(value = "/deleteLearningItem.htm")
	public String deleteLearningItem(String memberId, HttpServletRequest request) {
		try{
			String id = (String) request.getParameter("id");
			experBiz.deleteLearningById(Common.empty(id)?null:Integer.parseInt(id));
		}catch(Exception e){
			e.printStackTrace();
		}
		return memberExper(memberId,request);
	
	}
	
//	学习经历页面
	@RequestMapping(value = "/memberWorkItem.htm", method = RequestMethod.GET)
	public String memberWorkItem(HttpServletRequest request) {
		String id = (String) request.getParameter("id");
		try{
			Work w = experBiz.getWorkById(id==null?0:Integer.parseInt(id));
			request.setAttribute("work", w);

		}catch(Exception e){
			e.printStackTrace();
		}
		return "member/memberWorkItem";
	
	}
	
//	保存工作经历
	@RequestMapping(value = "/saveWorkItem.htm", method = RequestMethod.POST)
	public String saveWorkItem(String memberId, HttpServletRequest request,HttpServletResponse response) {
		response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
		try{
			pw = response.getWriter();
			Member member = (Member) request.getSession().getAttribute("member");
			String id = (String) request.getParameter("id");
			String unit = request.getParameter("unit");
			String department = request.getParameter("department");
			String entryDate = request.getParameter("entryDate");
			String departureDate = request.getParameter("departureDate");
			Work work = new Work();
			work.setId(Common.empty(id)?null:Integer.parseInt(id));
			if(memberId != null && !"".equals(memberId) && !member.getIdentifier().equals(memberId)){
				work.setMember(memberId);
			}else{
				work.setMember(member.getIdentifier());
			}
			work.setUnit(unit);
			work.setDepartment(department);
			work.setEntryDate(entryDate);
			work.setDepartureDate(departureDate);
			experBiz.saveWork(work);
			pw.print("success");
		}catch(Exception e){
			e.printStackTrace();
			pw.print("error");
		}
		return null;
	}
	
//	删除工作经历
	@RequestMapping(value = "/deleteWorkItem.htm", method = RequestMethod.GET)
	public String deleteWorkItem(String memberId, HttpServletRequest request) {
		try{
			String id = (String) request.getParameter("id");
			experBiz.deleteWorkById(Common.empty(id)?null:Integer.parseInt(id));
		}catch(Exception e){
			e.printStackTrace();
		}
		return memberExper(memberId, request);
	
	}

	//	经历保存
	@RequestMapping(value = "/saveExper.htm", method = RequestMethod.POST)
	public String saveExper(HttpServletRequest request,HttpServletResponse response) {
		Member member = (Member) request.getSession().getAttribute("member");
		Detail detail = null;
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        
		try{
			pw = response.getWriter();
			String escaped_json = request.getParameter("jsonData");
			String json=Encode.unescape(escaped_json);
			JSONObject jsonObject = JSONObject.fromObject(json);
			Map<String, Class<?>> m = new HashMap<String, Class<?>>();
			m.put("personalityList", Personality.class);
			m.put("workList", Work.class);
			m.put("learningList", Learning.class);
			detail =  (Detail) JSONObject.toBean(jsonObject, Detail.class,m);
			detail.setMember(member.getIdentifier());
//			List<Device> deviceList = scene.getDeviceList();
			experBiz.saveExper(detail);
			pw.print("success");
			
		}catch(Exception e){
			e.printStackTrace();
			pw.print("error");
		}
		return null;
	}
	
//	进入修改密码页面
	@RequestMapping(value = "/entrySetAccount.htm")
	public String entrySetAccount(String memberId, HttpServletRequest request,HttpServletResponse response) {
		try {
			Member member = (Member)request.getSession().getAttribute("member");
			if(memberId != null && !"".equals(memberId) && !member.getIdentifier().equals(memberId)){
				member = memberBiz.getMemberById(memberId);
				request.setAttribute("member", member);
			}
			String hostPwd = memberBiz.getHostPwdByDoorplate(member.getFamily());
			request.setAttribute("hostPwd", hostPwd);
			return "member/setAccount";
		} catch (AppBusinessException e) {
			e.printStackTrace();
			return "common/error";
		}
	}
	
	//保存修改的密码
	@RequestMapping(value = "/saveSetAccount.htm", method = RequestMethod.POST)
	public String saveSetAccount(String memberId,String email, String oldPassword, String password, HttpServletRequest request,HttpServletResponse response) {
		try{
			response.setContentType("text/html; charset=UTF-8");
			PrintWriter out = response.getWriter();
			Member member = (Member)request.getSession().getAttribute("member");
			//判读如果不是登录用户
			if(memberId != null && !"".equals(memberId) && !member.getIdentifier().equals(memberId)){
				member = memberBiz.getMemberById(memberId);
			}
			//如果和户主使用同一把钥匙
			if(oldPassword!=null && !"".equals(oldPassword)){
				//原始密码错误
				if(!member.getPassword().equals(Common.md5(Common.md5(oldPassword)))){
					out.print("oldPasswordError");
					return null;
				}
			}
			member.setEmail(email);
			member.setPassword(password);
			memberBiz.setAccount(member);
			out.print("success");
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 判断原始密码是否正确	
	 * @param oldPassword	原始密码
	 * @param memberId		会员ID
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/checkOldPassword.htm", method = RequestMethod.POST)
	public void checkOldPassword(String oldPassword, String memberId, HttpServletRequest request,HttpServletResponse response) {
		try{
			response.setContentType("text/html; charset=UTF-8");
			PrintWriter out = response.getWriter();
			Member member = (Member)request.getSession().getAttribute("member");
			//判读如果不是登录用户
			if(memberId != null && !"".equals(memberId) && !member.getIdentifier().equals(memberId)){
				member = memberBiz.getMemberById(memberId);
			}
			//原始密码错误
			if(!member.getPassword().equals(Common.md5(Common.md5(oldPassword)))){
				out.print("oldPasswordError");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 判断是否和户主使用同一把钥匙
	 * @param memberId	会员Id
	 * @param password	会员密码
	 * @param request
	 * @param response
	 * @throws AppBusinessException
	 */
	@RequestMapping(value = "/checkModifyPassword.ajax", method = RequestMethod.GET)
	public void checkPassword(String memberId, String password, HttpServletRequest request,
			HttpServletResponse response) throws AppBusinessException {
		try {
			response.setContentType("text/text; charset=UTF-8");
			PrintWriter out = response.getWriter();
			Member member = (Member) request.getSession().getAttribute("member");
			if(memberId != null && !"".equals(memberId) && !member.getIdentifier().equals(memberId)){
				member = memberBiz.getMemberById(memberId);
			}
			//如果是户主则不需验证
			if(member.getIsHost()){
				out.print(true);
				return;
			}
			if (Common.empty(password))
				return;
			List<Member> memberList = memberBiz.getParentListByDoorplate(member.getFamily());
			boolean pswNotExist = true;
			if(!member.getPassword().equals(Common.md5(Common.md5(password)))){
				for (Member me : memberList) {
					if(Common.md5(Common.md5(password)).equals(me.getPassword())){
						pswNotExist = false;
						break;
					}
				}
			}
			out.print(pswNotExist);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	// 修改邮箱时的邮箱验证
	@RequestMapping(value = "/checkModifyEmail.htm", method = RequestMethod.GET)
	public void checkEmail(String memberId, HttpServletRequest request,
			HttpServletResponse response) throws AppBusinessException {
		try {
			String email = request.getParameter("email");
			if (Common.empty(email))
				return;
			response.setContentType("text/text; charset=UTF-8");
			PrintWriter pw = null;
			pw = response.getWriter();
			Member member = (Member)request.getSession().getAttribute("member");
			if(memberId != null && !"".equals(memberId) && !member.getIdentifier().equals(memberId)){
				member = memberBiz.getMemberById(memberId);
			}
			if(member.getEmail().equals(email)){
				pw.print(true);
			}else{
				Member m = memberBiz.getMemberEmail(email);
				if (m != null) {
					pw.print(false);
				} else {
					pw.print(true);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * author Bruce Zhang
	 * @param request
	 * @param response
	 * @return	进入家管理的添加成员页面
	 * @throws IOException
	 */
	@RequestMapping(value = "/toAddFamilyMember.htm")
	public String toFamilyMember(HttpServletRequest request, HttpServletResponse response) {
		try{
			return "member/addFamilyMember";
		}catch(Exception e){
			e.printStackTrace();
			return "common/error";
		}
	}
	
	/**
	 * author Bruce Zhang
	 * @param request
	 * @param response
	 * @return	验证添加的成员的是否和户主使用同一把钥匙
	 * @throws IOException
	 */
	@RequestMapping(value = "/checkIsHostPassword.htm")
	public void checkIsHostPassword(String password, HttpServletRequest request, HttpServletResponse response) {
		try{
			response.setContentType("text/text; charset=UTF-8");
			PrintWriter out = response.getWriter();
			Member member = (Member)request.getSession().getAttribute("member");
			if(member.getPassword().equals(Common.md5(Common.md5(password)))){
				out.print(false);
			}else{
				out.print(true);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 在家的管理页面添加成员
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/addFamilyMember.htm", method = RequestMethod.POST)
	public String addMember(Member member, HttpServletRequest request, HttpServletResponse response) {
		try { 
			response.setContentType("text/html; charset=UTF-8"); 
			PrintWriter out = response.getWriter();
			Member host = (Member) request.getSession().getAttribute("member");
			member.setFamily(host.getFamily());
			// 添加家庭成员
			String path = request.getContextPath();
			String basePath = request.getScheme() + "://"
					+ request.getServerName() + ":"
					+ request.getServerPort() + path + "/";
			memberBiz.addMember(basePath, member);
			out.print("success");
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return "common/error";
		}
	}
	
	/**
	 * 切换用户
	 * @param request
	 * @param response
	 * @return	家的别的成员的帐号
	 * @throws IOException
	 */
	@RequestMapping(value = "/changeUser.htm", method = RequestMethod.GET)
	public String changeUser(String memberId, HttpServletRequest request, HttpServletResponse response) {
		try { 
			Member member = memberBiz.getMemberById(memberId);
			if (member == null) {
				return "common/error";
			} else {
				request.getSession(true).setAttribute("member", member);
				response.sendRedirect("family?id="+member.getFamily());
				request.getSession().removeAttribute("loginMemberList");
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "common/error";
		}
	}
	
	/**
	 * 切换用户
	 * @param request
	 * @param response
	 * @return	判断切换用户时是否和自己使用同一把钥匙
	 * @throws IOException
	 */
	@RequestMapping(value = "/changeUserPassword.htm", method = RequestMethod.GET)
	public String changeUserPassword(String memberId, HttpServletRequest request, HttpServletResponse response) {
		try { 
			response.setContentType("text/html; charset=UTF-8"); 
			PrintWriter out = response.getWriter();
			Member member = memberBiz.getMemberById(memberId);
			if (member == null) {
				return "common/error";
			} else {
				Member loginUser = (Member)request.getSession().getAttribute("member");
				//判断切换的用户是否和自己使用的同一把钥匙
				if(loginUser.getPassword().equals(member.getPassword())){
					out.print("same");
				}else{
					out.print("notSame");
				}
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "common/error";
		}
	}
	
	/**
	 * 切换用户
	 * @param request
	 * @param response
	 * @return	判断切换用户时输入的钥匙是否正确
	 * @throws IOException
	 */
	@RequestMapping(value = "/checkChangeUserPassword.htm", method = RequestMethod.POST)
	public String checkChangeUserPassword(String memberId, String password, HttpServletRequest request, HttpServletResponse response) {
		try { 
			response.setContentType("text/html; charset=UTF-8"); 
			PrintWriter out = response.getWriter();
			Member member = memberBiz.getMemberById(memberId);
			if (member == null) {
				return "common/error";
			} else {
				//判断切换的用户是否和自己使用的同一把钥匙
				if(member.getPassword().equals(Common.md5(Common.md5(password)))){
					out.print("success");
				}else{
					out.print("error");
				}
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "common/error";
		}
	}
	
}
